package cn.xing.managementSystem.service;

import cn.xing.managementSystem.domain.ImageStore;
import cn.xing.managementSystem.repository.ImageStoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.service
 * @class ImageStoreService
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/22 下午11:52
 * @description
 */

@Service
@Transactional
public class ImageStoreService {

    @Value("${image.boot.path}")
    private String imageBootPath;

    @Autowired
    private ImageStoreRepository imageStoreRepository;

    public ImageStore findById(Long id){
        return imageStoreRepository.findByIdAndAndDeletedIsFalse(id);
    }

    public ImageStore saveImageStore(ImageStore imageStore){
       return imageStoreRepository.saveAndFlush(imageStore);
    }

   public ImageStore saveImageStore(MultipartFile imageFile) throws IOException {
       String originalFilename = imageFile.getOriginalFilename();
       String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
       String imagePath = imageBootPath + UUID.randomUUID().toString() + fileFormat;
       File tempFile = new File(imagePath);
       if(!tempFile.exists()){
           tempFile.createNewFile();
       }
       imageFile.transferTo(tempFile);
       ImageStore imageStore = new ImageStore();
       imageStore.setOriginalName(originalFilename);
       imageStore.setPath(imagePath);
       return imageStoreRepository.saveAndFlush(imageStore);
   }
}